var user = null ; //当前登录账号
var toUserId = null ; //接收方的用户ID
var fromUserId = null ;//发送方的用户ID
$(function () {
    findUserSession(); //找用户session


    //查询所有用户
    findAllUsers();

    console.info(user);
    if(user!=null){
        fun_webSocket();
    }


    listenFile();


});

var webSocket = null ;
/**
 * 连接服务器
 */
function fun_webSocket(){
    var url = "ws://"+location.host+"/webSocket/"+user.userId;

    webSocket = new WebSocket(url);
    webSocket.onopen=function (ev) {
        console.info("连接成功");
        //$("#status_"+user.userId).css("color","green");

    }
    webSocket.onerror=function (ev) {
        alert("对不起,服务器异常!请刷新页面!");
    }
    webSocket.onmessage=function (ev) {
        var data = ev.data;
        var obj = JSON.parse(data);

        if(obj.status==1){ //上线
            $("#status_"+obj.userId).css("color","green");
        }else if(obj.status==0){ //下线
            $("#status_"+obj.userId).css("color","#ccc");
        }else if(obj.status==10 || obj.status==20){ //表示正常的聊天信息
            console.info("toUserId:"+toUserId+" fromUserId:"+fromUserId+"    bm-toUserId:"+obj.bm.toUserId+"  fromUserId: "+obj.bm.fromUserId);
            if((toUserId==obj.bm.toUserId && fromUserId==obj.bm.fromUserId)||
                (toUserId==obj.bm.fromUserId && fromUserId==obj.bm.toUserId )){

                if(obj.bm.fromUserId==user.userId){
                    if(obj.status==20){ //如果发送的是图片
                        $(".chat").append("<div class=\"bubble me\"><img src="+obj.bm.message+" alt='发送的图片' width='100' height='100'></div>");
                        //$(".chat").append("<div class=\"bubble me\"><a href="+obj.bm.message+" target='_blank'>点击查看文件</a></div>");

                    }else{
                        $(".chat").append("<div class=\"bubble me\">"+obj.bm.message+"</div>");
                    }

                }else{
                    if(obj.status==20) {
                        $(".chat").append("<div class=\"bubble you\"><img src="+obj.bm.message+" alt='发送的图片' width='100' height='100'></div>");
                        //$(".chat").append("<div class=\"bubble you\"><a href="+obj.bm.message+" target='_blank'>点击查看文件</a></div>");


                    }else{
                        $(".chat").append("<div class=\"bubble you\">" + obj.bm.message + "</div>");
                    }
                }
                console.info(obj.remark);
                if(typeof(obj.remark)!="undefined"){
                    $(".chat").append("<div class=\"conversation-start\">" +
                        "                    <span>"+obj.remark+"</span>" +
                        "                </div>")
                }
            }else{

                //不是当前界面的话,就需要在发送人的头像旁边加上标识
                var tid = obj.bm.fromUserId;
                var count = $("#mesCount_"+tid).html();
                if(count==""){
                    count = 1 ;
                }else{
                    count++;
                }
                $("#mesCount_"+tid).html(count);
                $("#mesCount_"+tid).addClass("mesCount");
            }

        }

    }
    webSocket.onclose=function (ev) {
        console.info("已经关闭");
    }
    webSocket.onerror=function (ev) {
        console.info("出错了......"+ev);
    }
}

/**
 * 查询是否已经登录
 */
function findUserSession() {
    var url = "ManagerServlet?action=findSession";

    $.ajax({
       url:url,
       data:null,
       dataType:'json',
        async:false,
        success:function (obj) {
            if(obj.state==0){
                location.href="login.html"
            }else{
                user = obj.pojo;
                $("#userName").html(user.userName);
                $("#remark").html(user.remark);
                $("#userId").val(user.userId);
            }
        }
    });
}

function findAllUsers(){
    $(".people").html("");
    var url = "ManagerServlet?action=queryAllUsers";
    $.post(url,null,function (obj) {
        $.each(obj,function(index,item){
            var color="";
            if(item.userStatus==1 || item.userId == user.userId){
                color="color:green";
            }else if(item.userStatus==0){
                color="color:#ccc";
            }
            $(".people").append('<li class="person" data-chat="'+item.userId+'" onclick=chatMain("'+item.userName+'","'+item.userId+'")>' +
                '                    <span class="phead">'+item.userName.substr(0,1)+'</span>' +
                '                    <span class="name">'+item.userName+'</span>' +
                '                    <span id=mesCount_'+item.userId+'></span> ' +
                '                    <span id=status_'+item.userId+' class="time" style="'+color+'">●</span>' +
                '                    <span class="preview">'+item.remark+'</span>' +
                '                </li>');

        })

    },"json");
}

/**
 * 点击好友头像时,需要执行的方法
 */
function chatMain(userName,userId){
    $("#userNameHead").html(userName);
    toUserId = userId ;
    fromUserId = user.userId ;
    //使用ajax调用聊天记录
    var url = "ManagerServlet?action=queryChatLogger";
    var data = {"fromUserId":fromUserId,"toUserId":toUserId}; //尽量显示最近的消息记录
    $(".chat").html("");
    $.post(url,data,function(obj){
        $.each(obj,function (index,item) {
            if(item.userSendId==fromUserId){
                $(".chat").append("<div class=\"bubble me\">"+item.loggerMessage+"</div>");
            }else{
                $(".chat").append("<div class=\"bubble you\">"+item.loggerMessage+"</div>");
            }
        })
    },"json");
}

/**
 * 发送消息
 */
function sendMsg(){
    if(webSocket.readyState!=1){
        alert("请刷新页面,重新连接服务器!");
        return ;
    }
    var mess = $("#txt_message").val();
    if(mess==""){
        alert("请输入信息!");
        return ;
    }
    var baseMessage = new Object();
    baseMessage.fromUserId = fromUserId;
    baseMessage.toUserId = toUserId;
    baseMessage.message = mess ;



    var json = JSON.stringify(baseMessage);

    webSocket.send(json);

    $("#txt_message").val("");
}

/**
 * 点击上传文件时触发
 */
function upFile() {
    if(toUserId==""){
        alert("请选择聊天的对方!");
        return ;
    }
    $("#attachFile").click();
}

/**
 * 监听文件上传
 */
function listenFile(){
    //选择文件之后,直接将文件上传至服务器
    $("#attachFile").on("change",function (e) {
        console.info($(this));

        //定义一个表单对象
        var formData = new FormData();
        formData.append("file",document.getElementById("attachFile").files[0]);
        formData.append("fromUserId",fromUserId);
        formData.append("toUserId",toUserId);

        $.ajax({
            url: "ManagerServlet?action=uploadFile",
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            dataType:"json",
            success : function(data) {
                document.getElementById("attachFile").value="";
                if(data.status==20){
                    console.info("发送成功!");
                }
            }
        });

    })
}

//点击城市
function cityWeather(city){
    var baseMessage = new Object();
    baseMessage.fromUserId = fromUserId;
    baseMessage.toUserId = toUserId;
    baseMessage.message = city ;
    var json = JSON.stringify(baseMessage);
    webSocket.send(json);
}